from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.models.Skillc2 import User, PointsRecord
from app import db
from datetime import datetime

points_bp = Blueprint('points', __name__)

@points_bp.route('/points/add', methods=['POST'])
@jwt_required()
def add_points():
    """添加积分"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()

        if not data or 'points' not in data or 'description' not in data:
            return jsonify({
                'status': 'error',
                'message': '缺少必要的字段'
            }), 400

        points = data['points']
        description = data['description']

        if not isinstance(points, int) or points <= 0:
            return jsonify({
                'status': 'error',
                'message': '积分必须是正整数'
            }), 400

        user = User.query.filter_by(UserId=current_user_id).first()
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404

        points_record = PointsRecord(
            UserId=current_user_id,
            Points=points,
            Description=description,
            CreateTime=datetime.now()
        )

        user.UserPoints = (user.UserPoints or 0) + points
        db.session.add(points_record)
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': '积分添加成功',
            'data': {
                'current_points': user.UserPoints
            }
        })

    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@points_bp.route('/points/balance', methods=['GET'])
@jwt_required()
def get_points_balance():
    """查询积分余额"""
    try:
        current_user_id = int(get_jwt_identity())
        user = User.query.filter_by(UserId=current_user_id).first()
        
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404

        return jsonify({
            'status': 'success',
            'data': {
                'points': user.UserPoints or 0
            }
        })

    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@points_bp.route('/points/history', methods=['GET'])
@jwt_required()
def get_points_history():
    """查询积分历史"""
    try:
        current_user_id = int(get_jwt_identity())
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)

        user = User.query.filter_by(UserId=current_user_id).first()
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404

        records = PointsRecord.query.filter_by(UserId=current_user_id)\
            .order_by(PointsRecord.CreateTime.desc())\
            .paginate(page=page, per_page=per_page)

        return jsonify({
            'status': 'success',
            'data': {
                'total': records.total,
                'pages': records.pages,
                'current_page': page,
                'per_page': per_page,
                'records': [{
                    'record_id': record.RecordId,
                    'points': record.Points,
                    'description': record.Description,
                    'create_time': record.CreateTime.strftime('%Y-%m-%d %H:%M:%S')
                } for record in records.items]
            }
        })

    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@points_bp.route('/points/reduce', methods=['POST'])
@jwt_required()
def reduce_points():
    """减少积分"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()

        if not data or 'points' not in data or 'description' not in data:
            return jsonify({
                'status': 'error',
                'message': '缺少必要的字段'
            }), 400

        points = data['points']
        description = data['description']

        if not isinstance(points, int) or points <= 0:
            return jsonify({
                'status': 'error',
                'message': '积分必须是正整数'
            }), 400

        user = User.query.filter_by(UserId=current_user_id).first()
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404

        # 检查积分是否足够
        if (user.UserPoints or 0) < points:
            return jsonify({
                'status': 'error',
                'message': '积分不足'
            }), 400

        # 创建积分记录（使用负值表示减少）
        points_record = PointsRecord(
            UserId=current_user_id,
            Points=-points,  # 负数表示减少积分
            Description=description,
            CreateTime=datetime.now()
        )

        # 更新用户积分
        user.UserPoints = user.UserPoints - points
        
        db.session.add(points_record)
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': '积分减少成功',
            'data': {
                'current_points': user.UserPoints,
                'points': points,
                'description': description,
                'create_time': points_record.CreateTime.strftime('%Y-%m-%d %H:%M:%S')
            }
        })

    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500 